<template>
  <div class="login-container">
    <h2>登录</h2>
    <input v-model="username" placeholder="用户名" />
    <input v-model="password" type="password" placeholder="密码" />
    <button @click="handleLogin">登录</button>
    <p v-if="errorMessage" style="color: red">{{ errorMessage }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/api'

const username = ref('')
const password = ref('')
const router = useRouter()
const errorMessage = ref('')

const handleLogin = async () => {
  try {
    const response = await api.post('/api/users/login', {
      username: username.value,
      password: password.value
    })
    localStorage.setItem('isLoggedIn', 'true')
    localStorage.setItem('token', response.token)
    router.push('/')
  } catch (error) {
    errorMessage.value = error.response?.data?.message || '登录失败，请重试'
    console.error('登录错误:', error)
  }
}
</script>

<style scoped>
.login-container {
  max-width: 300px;
  margin: 100px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  text-align: center;
}

.login-container input {
  width: 100%;
  margin-bottom: 10px;
  padding: 8px;
}

.login-container button {
  width: 100%;
  padding: 10px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
</style>